package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet(name = "SignonServlet", value = "/signon")
public class SignonServlet extends HttpServlet {

    private static final String MAIN = "/WEB-INF/jsp/catalog/Main.jsp";
    private static final String SIGNON = "/WEB-INF/jsp/account/SignonForm.jsp";

    private Account account;
    private String username;
    private String password;
    private boolean authenticated = false;
    private String code;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String token =(String)request.getSession().getAttribute(KAPTCHA_SESSION_KEY);//获取验证码
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);//删除验证码

        AccountService accountService = new AccountService();
        username = request.getParameter("username");
        password = request.getParameter("password");
        code = request.getParameter("code");

        account = accountService.getAccount(username, password);

        if(account == null){
            request.setAttribute("msg","Invalid username or password.  Signon failed.");
            account = new Account();
            List<Product> myList = null;
            authenticated = false;
            request.getRequestDispatcher(SIGNON).forward(request,response);
        }
        else if (token == null || !token.equalsIgnoreCase(code)){
            request.setAttribute("codeError","Invalid Verification code or Verification code is empty.");
            request.getRequestDispatcher(SIGNON).forward(request,response);
        }
        else {
            HttpSession session = request.getSession();
            Cart cart = new Cart();
            String userid = account.getUsername();
            List<CartItem> cartItemList = cart.getCartItemListByUserid(userid);
            for (int i = 0; i < cartItemList.size(); i++){
                CartItem cartItem = cartItemList.get(i);
                cart. addItem1(cartItem);
            }
            session.setAttribute("cart", cart);

            session.setAttribute("username", account.getUsername());

            account.setPassword(null);

            CatalogService catalogService = new CatalogService();
            List<Product> myList = catalogService.getProductListByCategory(account.getFavouriteCategoryId());
            authenticated = true;

            session.setAttribute("account",account);
            session.setAttribute("myList",myList);
            session.setAttribute("authenticated",authenticated);
            session.setAttribute("msg", null);

            if(account != null){
                HttpServletRequest httpRequest= request;
                String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

                LogService logService = new LogService();
                String logInfo = logService.logInfo(" ") + strBackUrl + " 用户登录";
                logService.insertLogInfo(account.getUsername(), logInfo);
            }

            response.sendRedirect(request.getContextPath()+"/main");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

}
